﻿using System;
using System.Collections.Generic;
using NHibernate;
using OigSync.Infrastructure.Repository;
using OigSync.Infrastructure.Domain;

namespace OigSync.Infrastructure.Repository.Hbm
{
    public class RepositoryHbmImpl<T> : IRepository<T> where T : EntityBase
    {
        /*
         * Hibernate Session 工厂
         */
        public ISessionFactory SessionFactory { get; set; }
 
        [ThreadStatic]
        private static ISession session;


        protected ISession Session
        {
            get {
                if (session == null)
                    session = SessionFactory.OpenSession();

                return session;
            }
        }

        /*
        * 从持久层延迟载入对象
        */
        public T Load(Object key)
        {
            return Session.Load<T>(key);
        }

        /*
         * 从持久层即时载入对象
         */
        public T Get(Object key)
        {
            return Session.Get<T>(key);
        }

        /*
         * 从持久层获取所有对象
         */
        public IList<T> GetAll()
        {
            return Session.CreateCriteria(typeof(T)).List<T>();
        }

        /*
         * 保存对象到持久层
         */
        public void Save(T entity)
        {
            Session.Save(entity);
        }

        /*
         * 更新持久层对象
         */
        public void Update(T entity)
        {
            Session.SaveOrUpdate(entity);
        }

        /*
         * 删除持久层对象
         */
        public void Delete(T entity)
        {
            Session.Delete(entity);
        }
    }
}